package dom4j.game;

import dom4j.TestA_DOM4J;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

public class GameDao {

    public List<Game> getAll() throws Exception {
        URL url = new URL("http://www.people.com.cn/rss/politics.xml");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        List<Game> games = new ArrayList<>();
        SAXReader reader = new SAXReader();
//        Document document = reader.read(GameDao.class.getClassLoader().getResourceAsStream("politics.xml"));
        Document document = reader.read(conn.getInputStream());
        Element root = document.getRootElement();
        List<Element> elementList = root.element("channel").elements("item");
        for (Element element:elementList){
            Game game = new Game();
            games.add(game);
            game.setAuthor(element.elementText("author"));
            game.setTitle(element.elementText("title"));
            game.setLink(element.elementText("link"));
            game.setPubDate(Date.valueOf(element.elementText("pubDate")));
        }

        return games;
    }
}
